﻿using System;
using GalaSoft.MvvmLight.Messaging;
using Ninject;
using Ninject.Parameters;

namespace JustinAngel.UnitedNationsNews.Framework
{
    public static class IoC
    {
        private static StandardKernel container = new StandardKernel();

        public static void Register<TFrom, TTo>()
            where TTo : TFrom
            where TFrom : class
        {
            container.Bind<TFrom>().To<TTo>();
        }

        public static void Register(Type from, Type to)
        {
            container.Bind(from).To(to);
        }

        public static void Register(Type from, object instance)
        {
            container.Bind(from).ToConstant(instance);
        }

        public static T Get<T>()
           where T : class
        {
            var result = container.Get<T>();

            if (result == null && typeof(T) == typeof(IMessenger))
                return (T)(object)Messenger.Default;

            return result;
        }

        public static object Get(Type type)
        {
            return container.Get(type);
        }

        public static void Register<T>(T instance)
        {
            container.Bind<T>().ToConstant(instance);
        }

        public static void BuildUp<T>(T t)
        {
            container.Inject(t);
        }

        public static void Clear()
        {
            container = new StandardKernel();
        }

        public static bool IsRegistered(Type type)
        {
            return container.CanResolve(container.CreateRequest(type, binding => true, new IParameter[] {}, false, false));
        }
    }

}
